package com.rytong.tools.ui.chart;

import com.rytong.tools.ui.Component;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;

public class CustomSeekBar extends View {

    private Paint paint_;
    /**
     * 矩形框
     */
    private Rect rect;
    /**
     * 轨道背景
     */
    private GradientDrawable trackdrawable;
    /**
     * 滑块中 三角形颜色
     */
    private int triangleColor_;
    private Path path_;
    /**
     * 指头所在位置X坐标
     */
    private float fingers_coordinates_;
    /**
     * 滑块中矩形框颜色
     */
    private int rectColor_;
    /**
     * 滑块宽度
     */
    int sliderWidth_ = 0;
    /**
     * 绘制垂直线所用的view
     */
    LPBackgroundLayout lineView_;
    /**
     * 和seekbar事件绑定的图表
     */
    Component chart_;
    /**
     * 图表外层套的scrollview，用于计算滑动后的偏移量
     */
    HorizontalScrollView scrollView_;
    /**
     * 记录上一个响应onClick事件的Li
     */
    private LITag previousLi_;
    /**
     * 图表的类型 1 -- 折线图 | 气泡图； 0 -- 柱状图
     */
    private int chartType_ = 0;
    private int offset_;

    public CustomSeekBar(Context context) {
        super(context);
        paint_ = new Paint();
        paint_.setAntiAlias(true);
        triangleColor_ = Color.parseColor("#F18000");
        rectColor_ = Color.parseColor("#7D7E7F");

        int[] colors = new int[] { Color.WHITE, Color.WHITE, Color.GRAY };
        trackdrawable = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, colors);
        trackdrawable.setGradientType(GradientDrawable.RECTANGLE);
        int radii = 8;
        trackdrawable.setCornerRadii(new float[] { radii, radii, radii, radii, radii, radii, radii, radii });

        rect = new Rect();
        path_ = new Path();
    }

    public CustomSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint_ = new Paint();
        paint_.setAntiAlias(true);
        triangleColor_ = Color.parseColor("#F18000");
        rectColor_ = Color.parseColor("#7D7E7F");

        int[] colors = new int[] { Color.WHITE, Color.WHITE, Color.GRAY };
        trackdrawable = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, colors);
        trackdrawable.setGradientType(GradientDrawable.RECTANGLE);
        int radii = 8;
        trackdrawable.setCornerRadii(new float[] { radii, radii, radii, radii, radii, radii, radii, radii });

        rect = new Rect();
        path_ = new Path();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        trackdrawable.setBounds(getPaddingLeft(), getHeight() / 5, getWidth() - getPaddingRight(), getHeight() * 4 / 5);
        trackdrawable.draw(canvas);
        // 绘制轨道矩形边框
        // rect.set(getPaddingLeft(), getHeight() / 5, getWidth() - getPaddingRight(), getHeight() * 4 / 5);
        // paint_.setColor(rectColor_);
        // paint_.setStyle(Style.STROKE);
        // canvas.drawRect(rect, paint_);

        // 锁定操作区域，保证不影响其他地方。
        // tips：save函数把当前的绘制状态推进栈里，而restore函数则把最后一个状态弹出栈。
        canvas.save();
        // 绘制滑块
        float offset = fingers_coordinates_ - (sliderWidth_ >> 1);
        if (offset < 0) {
            offset = 0;
        } else if (offset > getWidth() - sliderWidth_) {
            offset = getWidth() - sliderWidth_;
        }
        canvas.translate(offset, 0);
        rect.set(0, 0, sliderWidth_, getHeight());
        paint_.setColor(rectColor_);
        paint_.setAlpha(200);
        paint_.setStyle(Style.FILL);
        canvas.drawRect(rect, paint_);
        // 绘制三角形
        paint_.setColor(triangleColor_);
        path_.moveTo(0, getHeight() * 2 / 3);
        path_.lineTo(sliderWidth_ >> 1, getHeight() / 3);
        path_.lineTo(sliderWidth_, getHeight() * 2 / 3);
        path_.close();
        canvas.drawPath(path_, paint_);

        canvas.restore();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        fingers_coordinates_ = event.getX();
        switch (action) {
        case MotionEvent.ACTION_DOWN:
            disposeSlippingEvent(fingers_coordinates_);
            break;
        case MotionEvent.ACTION_MOVE:
            disposeSlippingEvent(fingers_coordinates_);
            break;
        case MotionEvent.ACTION_UP:
            disposeSeekbarUpEvent(fingers_coordinates_);
            break;
        default:
            break;
        }
        if (lineView_ != null && scrollView_ != null) {
            lineView_.setLine_X_coordinate_(fingers_coordinates_ - (sliderWidth_ >> 1) + scrollView_.getScrollX());
        }
        invalidate();
        return true;
    }

    private void disposeSlippingEvent(float x_coordinates) {
        if (chart_ == null)
            return;
        x_coordinates -= (sliderWidth_ >> 1);
        x_coordinates = x_coordinates < 0 ? 0 : x_coordinates;
        if (scrollView_ != null) {
            x_coordinates += scrollView_.getScrollX();
        }
        if (previousLi_ != null && chartType_ == 0) {
            // 保证滑块经过柱状图的每条柱子时只响应一次
            if ((int) x_coordinates < previousLi_.left_
                    || (int) x_coordinates > (previousLi_.left_ + previousLi_.width_)) {
                previousLi_ = null;
            }
        } else if (previousLi_ != null && chartType_ == 1) {
            // 保证滑块经过折线图的每个点的时候只响应一次。
            int offset = 0;
            if(previousLi_.needDrawPoint_){
            	offset = previousLi_.width_ >> 1;
            }
            if((int) x_coordinates < previousLi_.left_ - offset
            	|| (int) x_coordinates > (previousLi_.left_ + offset)){
            	previousLi_ = null;
            }
        }
        int size = chart_.childrenList_.size();
        LITag li = null;
        for (int i = 0; i < size; i++) {
            li = (LITag) chart_.childrenList_.get(i);
            if (chartType_ == 1) {
                int offset = 0;
                if (li.needDrawPoint_) {
                    offset = li.width_ >> 1;
                }
                if ((int) x_coordinates >= li.left_ - offset && (int) x_coordinates <= li.left_ + offset) {
                	// 判断一下，如果是同一个li，就不再调用li的onclick方法了。
                	if (li == previousLi_) {
                	    break;
                	}
                	previousLi_ = li;
                    li.onClick();
                    break;
                }
            } else {
                if ((int) x_coordinates >= li.left_ && (int) x_coordinates <= (li.left_ + li.width_)) {
                    if (li == previousLi_) {
                        break;
                    }
                    previousLi_ = li;
                    li.onClick();
                    break;
                }
            }
        }
    }

    /**
     * 使seekbar滑块松开后自动弹回最近位置
     * 
     * @param x_coordinates
     */
    private void disposeSeekbarUpEvent(float x_coordinates) {
        if (chart_ == null)
            return;
        x_coordinates -= (sliderWidth_ >> 1);
        x_coordinates = x_coordinates < 0 ? 0 : x_coordinates;
        if (scrollView_ != null) {
            x_coordinates += scrollView_.getScrollX();
        }
        int size = chart_.childrenList_.size();
        LITag temp = null;
        LITag li = null;
        LITag nearest = null;
        for (int i = 0; i < size; i++) {
            li = (LITag) chart_.childrenList_.get(i);
            if (x_coordinates == li.left_)
                break;
            if (i == 0) {
                // 若手指按下的x坐标位于第一个Li附近
                if (x_coordinates < li.left_) {
                    nearest = li;
                    break;
                } else {
                    temp = (LITag) chart_.childrenList_.get(i + 1);
                    if (x_coordinates - li.left_ < ((temp.left_ - li.left_) >> 1)) {
                        nearest = li;
                        break;
                    }
                }
                continue;
            }
            if (i == size - 1) {
                // 若手指按下的x坐标位于最后一个Li附近
                if (x_coordinates > li.left_) {
                    nearest = li;
                    break;
                } else {
                    temp = (LITag) chart_.childrenList_.get(i - 1);
                    if (li.left_ - x_coordinates < ((li.left_ - temp.left_) >> 1)) {
                        nearest = li;
                        break;
                    }
                }
                continue;
            }
            // 若手指按下的x坐标位于当前点的右侧侧且离当前点的距离小于到后一点的距离,则：……
            temp = (LITag) chart_.childrenList_.get(i + 1);
            if (li.left_ < x_coordinates && Math.abs(li.left_ - x_coordinates) < Math.abs((li.left_ - temp.left_) >> 1)) {
                nearest = li;
                break;
            }
            // 若手指按下的x坐标位于当前点的左侧且离当前点的距离小于到前一点的距离,则：……
            temp = (LITag) chart_.childrenList_.get(i - 1);
            if (li.left_ >= x_coordinates && li.left_ - x_coordinates < ((li.left_ - temp.left_) >> 1)) {
                nearest = li;
                break;
            }
        }
        if (nearest != null) {
            fingers_coordinates_ = nearest.left_ - scrollView_.getScrollX() + (sliderWidth_ >> 1);
            if (chartType_ == 0 && nearest.width_ > 0) {
                fingers_coordinates_ += (nearest.width_ >> 1);
            }
            if (nearest != previousLi_) {
                // 若滑块滑动到li上松开手指就只执行move中的onClick方法
                nearest.onClick();
            }
        }
    }

    /**
     * 关联图表和seekbar控件并判断图表类型
     * 
     * @param lastChart
     * @param horizontalScrollView
     */
    public void setChartAndScrollView(Component lastChart, HorizontalScrollView scrollView) {
        chart_ = lastChart;
        scrollView_ = scrollView;
        if (chart_ instanceof LPLinePlotLayout || chart_ instanceof LPBallPlotLayout) {
            chartType_ = 1;
        }
        if (chart_ != null && chart_.childrenList_ != null && scrollView_ != null) {
            int size = chart_.childrenList_.size();
            LITag li = null;
            LITag selectedLi = null;
            for (int i = 0; i < size; i++) {
                li = (LITag) chart_.childrenList_.get(i);
                if (li.selected_) {
                    selectedLi = li;
                    break;
                }
            }
            if (selectedLi != null) {
                int displayWidth = this.getLayoutParams().width - (sliderWidth_ >> 1);
                if(selectedLi.left_ > displayWidth){
                    offset_ = selectedLi.left_ + selectedLi.width_ + selectedLi.width_ / 2 - displayWidth;
                    fingers_coordinates_ = displayWidth;
                }else{
                    fingers_coordinates_ = selectedLi.left_ + (sliderWidth_ >> 1);
                    if (chartType_ == 0 && selectedLi.width_ > 0) {
                        fingers_coordinates_ += (selectedLi.width_ >> 1);
                    }
                }
            }
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        // TODO Auto-generated method stub
        super.onSizeChanged(w, h, oldw, oldh);
        scrollView_.scrollTo(offset_, 0);
    }
}
